import * as React from 'react';
import {Text, View, StyleSheet, TouchableOpacity, ImageBackground, Image,ScrollView} from 'react-native';
import {useNavigation,useRoute} from '@react-navigation/native'
import {useState, useEffect, useRef} from 'react';
import screen from '../../utils/screen';
import Images from '../../images/images';
import DeviceListItem from '../../components/deviceListItem';
import {useHeaderHeight} from '@react-navigation/elements'
import AppStore, {useAppStore} from '../../store/useAppStore';
import BleUtil from '../../utils/bleUtil';
import BleManager, {BleState} from 'react-native-ble-manager';
import NativeUtil, {isIos} from '../../utils/native';
import RNLocation from 'react-native-location';
import store from 'react-native-simple-store';
import TouchableView from '../../components/touchableView';
import {useToast} from '../../components/toast/useToast';
import LinkButton from '../../components/linkButton';
import MessageItem from '../../components/messageItem';
import {formatTimestamp} from '../../utils/dateUtil';
import {useDialog} from '../../components/dialog/useDialog';
import Battery from '../../components/battery';
import loading from '../../components/loading/loading';
import {getSatMsgCmd, setGpsInfoCmd} from '../../utils/bleCmd';

const Home = ()=>{

    const navigation = useNavigation()

    const route = useRoute()
    const toast = useToast()
    const dialog = useDialog()
    const {appState:{deviceList,currentDevice,msgList,battery,location},updateAppState} = useAppStore()
    const headerHeight = useHeaderHeight()
    const locRef = useRef(null)
    console.log('home appState:',{currentDevice,deviceList,msgList});

    useEffect(()=>{

        navigation.setOptions({
            headerRight:()=>(
                <TouchableOpacity
                    style={{paddingRight:screen.PIXEL_30}}
                    onPress={()=>{
                        // navigation.navigate('Help')
                    }}
                >
                    <Image source={Images.custom_service} style={{width:screen.PIXEL_40,height:screen.PIXEL_40}}/>
                </TouchableOpacity>
            ),
        })

        accessLocation()
        initBle()

        const stateListener = BleUtil.addUpdateStateListener((args)=>{
            console.log('home BleManagerDidUpdateState:',args);
            let bluetoothEnable = (args.state === 'on')
            updateAppState({bluetoothEnable})
            if(!bluetoothEnable){
                updateAppState({currentDevice:null})
            }
        })

        //监听设备断开连接
        const disconnectListener = BleUtil.addDisconnectListener((args)=>{
            console.log('home disconnect:',args);
            if(!currentDevice) return

            updateAppState({currentDevice:null})
            dialog.alertConfirm('连接已断开，请重新连接终端',()=>{
                connect(args.peripheral)
            })
        })

        const notifyListener = BleUtil.addNotifyListener(handleNotify)

        if(isIos()) {
            NativeUtil.requestPressure(data => {
                console.log('pressure:', data);
                if (data.pressure) {
                    updateAppState({pressure:parseInt(data.pressure) })
                }
            })
        }

        getConnectDevice()

        return ()=>{
            stateListener.remove()
            notifyListener.remove()
            disconnectListener.remove()
        }

    },[])


    const handleNotify = (info,cmd)=>{
        console.log('home listen notify:',cmd,info);
        if(info.includes('seq')){
            let resultArr = info.split(' ')
            let lastStr = resultArr[resultArr.length - 1]
            var regex = /(?<=\[)(.+?)(?=\])/g;
            let seq = lastStr.match(regex)[0]
            console.log('seq：',seq);
            if(seq === '10'){
                console.log('setGpsInfo:',info);
            }
            if(seq === '20'){

            }
        }

        if(info.includes('battery')){
            const battery = info.replace('battery:','')
            console.log('电量',battery);
            if(parseInt(battery)){
                updateAppState({battery})
            }
        }
    }



    useEffect(()=>{
        getConnectDevice()
    },[deviceList])


    const accessLocation = async ()=>{
        RNLocation.requestPermission({
            ios:'whenInUse',
            android:{
                detail: "coarse"
            }
        }).then(granted => {
            console.log(granted);
            if(granted){
                startLoc()
            }
        })

    }

    function startLoc(){
        RNLocation.subscribeToLocationUpdates(locations => {
            let loc = locations[0]
            if(!locRef.current){
                store.save('loc',loc)
                updateAppState({location:loc})
                locRef.current = loc
                console.log('loc:',loc);
            }
        })


    }

    const initBle = ()=>{
        BleUtil.init().then(() => {
            // Success code
            BleUtil.checkState().then(state => {
                console.log('蓝牙状态:', state)
                if (state === BleState.On) {
                    updateAppState({bluetoothEnable: true})

                }
            })

        }).catch(e=>{
            console.log('ble err:',e)
        });
    }


    useEffect(()=>{
        console.log('currentDevice effect:',currentDevice);
        if(currentDevice){
            if(isTabe01()) return
            getSysInfo()
            setTimeout(()=>{
                setGpsInfo()
            },500)
            setTimeout(()=>{
                getMsgList()
            },1000)

        }else{
            updateAppState({
                msgList:[]
            })
        }
    },[currentDevice])


    const getMsgList = ()=>{
        let key = currentDevice.id + '_message'
        store.get(key).then(res=>{
            if(res){
                console.log(key,res);
                updateAppState({
                    msgList:res
                })
            }
        })


    }


    const connect = (deviceId)=>{

        let device = deviceList.find(item=>{return item.id === deviceId})
        if(!device) return
        loading.show('连接中')
        BleUtil.connectAndPrepare(device.id).then((info)=>{
            updateAppState({
                currentDevice: device
            })
            loading.hide()
        }).catch(error=>{
            loading.hide()
            let message = error.error === 'timeout' ? '连接超时' : '连接失败'
            toast.show(message)
        })

    }

    const getSysInfo = ()=>{
        //防止发送指令执之前就已经断开了链接
        if(!BleUtil.writeServiceUUID || !BleUtil.writeCharacteristicUUID) return
        sendCmd('getSysInfo\r\n')

    }

    const setGpsInfo = ()=>{
        if(!location) return
        let cmd = setGpsInfoCmd(location)
        // console.log(cmd);
        sendCmd(cmd)
    }

    const sendCmd = (cmd)=>{
        if(!currentDevice) return
        if(!isTabe01()){
            BleUtil.writeWithoutResponse(currentDevice.id,cmd).then(()=>{
                console.log(cmd);
            }).catch(error=>{
                console.log('write error:',error);
            })
        }else{
            BleUtil.write(currentDevice.id,cmd).then(()=>{
                console.log(cmd);
            }).catch(error=>{
                console.log('write error:',error);
            })
        }

    }

    const isTabe01 = ()=>{

        return currentDevice && currentDevice.name.includes('TABE01')
    }

    const getConnectDevice = ()=>{

        deviceList.forEach(item=>{
            BleUtil.isPeripheralConnected(item.id).then((connect) => {
                // Success code
                if(connect){
                    updateAppState({currentDevice:item})
                }
                console.log("isConnected: ",connect );
            });
        })


    }

    return (
        <ImageBackground
            source={Images.home_bg}
            imageStyle={{width:screen.width,height:'100%'}}
            style={[styles.container ]}
        >

            <TouchableView
                style={[styles.deviceBg,{marginTop:headerHeight}]}
                onPress={()=>{
                    navigation.navigate('DeviceManage')
                }}
            >
                {
                    currentDevice ? (
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                            <Text numberOfLines={1} style={{width:200}}>当前终端：{currentDevice.name}</Text>
                            {
                                battery ? (
                                    <Battery battery={battery}/>
                                ) : null
                            }
                        </View>

                    ):(
                        <Text style={{color:'#999'}}>当前终端：未连接</Text>
                    )
                }
                <Image style={{width:screen.PIXEL_20,height:screen.PIXEL_20}} source={Images.right2} resizeMode={'contain'}/>
            </TouchableView>

            {
                currentDevice ? (

                    <ScrollView
                        style={{marginVertical:screen.PIXEL_30}}
                        contentContainerStyle={{paddingHorizontal:screen.PIXEL_30}}
                    >
                        {
                            msgList.map((msg,index)=>{
                                return (
                                    <MessageItem
                                        key={index.toString()}
                                        data={msg}
                                        index={index}
                                    />
                                )
                            })
                        }

                    </ScrollView>
                ):(
                    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                        <Image source={Images.no_device} style={styles.emptyImg}/>
                        <Text style={styles.emptyText}>请连接卫星终端</Text>
                        <LinkButton
                            style={{marginTop:screen.PIXEL_50,alignSelf:'center'}}
                            title={ '连接终端'}
                            onPress={()=>{
                                navigation.navigate('DeviceManage')
                            }}
                        />
                    </View>
                )

            }

            {
                currentDevice ? (
                    <LinkButton
                        style={{marginBottom:screen.PIXEL_50,alignSelf:'center'}}
                        title={ '新建短信'}
                        onPress={()=>{
                            if(msgList.length>5){
                                toast.show('短信已经满了')
                                return
                            }
                            navigation.navigate('MessageEdit',{no:msgList.length})
                        }}
                    />
                ) : null
            }


        </ImageBackground>
    )
}
export default Home
const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    deviceBg:{
        height:screen.PIXEL_90,borderRadius:screen.PIXEL_100,borderWidth:0.3,borderColor:'#999',
        flexDirection:'row',justifyContent:'space-between',alignItems:'center',paddingHorizontal:screen.PIXEL_30,marginHorizontal:screen.PIXEL_20
    },
    emptyImg:{
        width:screen.PIXEL_240,height:screen.PIXEL_240
    },
    emptyText:{
        color:'#89A3BB',fontSize:14,marginTop:screen.PIXEL_50
    }
})
